'''
普通的常用工具

'''

import os
import json
import chardet
import torch
from tqdm import tqdm
from PIL import Image
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import cv2
import matplotlib.pyplot as plt
import pywt

# 读取数据，返回[(image, describe, label)]元组列表
def read_from_file(csv_path,image_path):
    data = []
    df = pd.read_csv(csv_path)
    print('----- [Loading]')
    for index, row in tqdm(df.iterrows()):
        left_image_filename, right_image_filename, describe = row['Left-Fundus'], row['Right-Fundus'], row['Description']
        
        left_image_path = image_path + '/' + left_image_filename
        right_image_path = image_path + '/' + right_image_filename
        
        label = df.loc[index, ['N','D','G','C','A','H','M','O']]
        label = label.to_numpy(dtype=np.float32)
        label = torch.tensor(label)
        
        data.append((left_image_path, right_image_path, describe, label))

    return data

# 分离训练集和验证集
def train_val_split(data, val_size=0.2):
    return train_test_split(data, train_size=(1-val_size), test_size=val_size)

# 写入数据
def write_to_file(path, outputs):
    df = pd.read_csv(path)
    df['predict'] = outputs
    df.to_csv(path,index=False)

# 保存模型
def save_model(output_path, model_type, model,model_name='pytorch_model.bin'):
    output_model_dir = os.path.join(output_path, model_type)
    if not os.path.exists(output_model_dir): os.makedirs(output_model_dir)    # 没有文件夹则创建
    model_to_save = model.module if hasattr(model, 'module') else model     # Only save the model it-self
    output_model_file = os.path.join(output_model_dir, model_name)
    torch.save(model_to_save.state_dict(), output_model_file)